#include "../include/client.h"
#include "../include/func.h"

int create_connect(int port,const char* ip){
    int clientfd=socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;
    memset(&addr,0,sizeof(addr));
    addr.sin_family=AF_INET;
    addr.sin_port=htons(port);
    addr.sin_addr.s_addr=inet_addr(ip);
    connect(clientfd,(struct sockaddr*)&addr,sizeof(addr));
    return clientfd;
}

int main(int argc, char* argv[]){
    //检测参数个数
    ARGS_CHECK(argc, 3);
    //与服务器端建立连接
    int port=atoi(argv[2]);
    int clientfd=create_connect(port,argv[1]);
    printf("%d has connected!\n",clientfd);
///////////////////////////////////////////////////////

    regisAndlogin_client(clientfd);


////////////////////////////////////////////////////////
    //buf1用于从键盘读取指令
    char buf1[BUFFSIZE];
    //用户登录
    userLogin(clientfd);

    while(1){
        //清理缓冲区
        memset(buf1, 0, sizeof(buf1));
        //从键盘读取CMD命令
        int ret=read(STDIN_FILENO, buf1, sizeof(buf1));
        ERROR_CHECK(ret, -1, "read");
        //将指令转化为私有协议
        cmd_t *cmd = analyzeCmd(buf1, strlen(buf1));
        if(cmd == NULL){
            printf("错误指令%s\n", buf1);
            continue;
        }
        //向服务端发送指令
        ret=send(clientfd, cmd, sizeof(cmd_t), 0);
        if(ret == 0)
        {
            puts("connect is broken!");
            exit(1);
        }
        ERROR_CHECK(ret, -1, "send");

        //利用cmdTy函数将字符类型转换为宏,再利用switch进行判断
        switch(cmd->cmd){
        case CMD_TYPE_LS:
        case CMD_TYPE_LL:
            handleOrder(clientfd);
            break;
        case CMD_TYPE_PWD: 
            pwd_client(clientfd);
            break;
        case CMD_TYPE_CP:
            cp_client(clientfd);
            break;
        case CMD_TYPE_CD:
            cd_client(clientfd);
            break;
        case CMD_TYPE_MV:
            mv_client(clientfd);
            break;
        case CMD_TYPE_RM:
            rm_client(clientfd);
            break;
        case CMD_TYPE_MKDIR:
            printf("mkdir done.");
            break;
        case CMD_TYPE_PUTS:
            handlePuts(clientfd, cmd->args[0].arg);
            break;
        case CMD_TYPE_GETS:
            //handleGets(clientfd);
            getsfileplus_client(clientfd,cmd->args[0].arg);
            break;                                   
        case CMD_TYPE_EXIT:
            close(clientfd);
            exit(0);
            break;
        default:
            break;
        }
        //用完指令以后将其free
        free(cmd);
    }
    close(clientfd);
    return 0;
}

